<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="100px">
      <el-form-item label="授权码" prop="key">
        <el-input v-model.trim="queryParams.key" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="token" prop="token">
        <el-input v-model.trim="queryParams.token" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="是否开了爬虫" prop="useSpider">
        <el-select v-model="queryParams.useSpider" placeholder="请选择" clearable style="width: 240px">
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="日期" prop="cabinetNo">
        <el-date-picker
          v-model="queryParams.date"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5" v-if="ids.length > 0">
        <el-button type="danger" plain icon="Delete" @click="batchDelete">批量删除</el-button>
      </el-col>

      <el-col :span="1.5" v-if="ids.length > 0">
        <el-button type="primary" plain @click="batchUpdate">批量更新</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain @click="exportAll">导出筛选数据</el-button>
      </el-col>
      <right-toolbar :search="false" v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" :align="`center`" />

      <el-table-column label="授权码" prop="key" width="300">
        <template #default="{ row }">
          <span
            @click="checkAccount(row)"
            class="on-default"
            :class="{
              'on-success': row.online === true,
              'on-error': row.online === false,
            }"
            >{{ row.key }}</span
          >
        </template>
      </el-table-column>
      <el-table-column label="token" prop="token" width="400">
        <template #default="{ row }">
          <span
            :class="{
              'on-success': row.online === true,
              'on-error': row.online === false,
            }"
            >{{ row.token }}</span
          >
        </template>
      </el-table-column>
      <el-table-column label="调用次数" prop="pCount"> </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="180"> </el-table-column>
      <el-table-column label="最大用户数" prop="maxUser" width="180"> </el-table-column>
      <el-table-column label="是否开了爬虫" prop="useSpider" width="180">
        <template #default="{ row }">
          <el-tag :type="row.useSpider == '0' ? 'success' : 'danger'">{{ row.useSpider == "0" ? "否" : "是" }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="更新时间" prop="updateTime" width="180">
        <template #default="{ row }">
          <span>{{ row.updateTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="备注" prop="remark" width="160"> </el-table-column>
      <el-table-column label="菜单id" prop="guildId" width="180"> </el-table-column>
      <el-table-column label="频道id" prop="channelId" width="180"> </el-table-column>
      <el-table-column label="操作" :align="`center`" class-name="small-padding fixed-width" width="200">
        <!-- 未结算才能启用 -->
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="校验账号" placement="top">
            <el-button link type="primary" icon="Service" @click="checkAccount(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="danger" icon="Delete" @click="deleteHandler(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      v-show="total > 0"
      :total="total"
      v-model:page="pagination.current"
      v-model:limit="pagination.size"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="roleRef" :inline="false" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="授权码" prop="key">
          <el-input :disabled="title === '修改'" v-model.trim="form.key" placeholder="请输入授权码" />
        </el-form-item>

        <el-form-item label="token" prop="token">
          <el-input v-model.trim="form.token" placeholder="请输入token" />
        </el-form-item>

        <el-form-item label="账号类型" prop="type">
          <el-select v-model="form.type" placeholder="账号类型" clearable style="width: 240px">
            <el-option v-for="dict in MAP.categoryMap" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="菜单id" prop="guildId">
          <el-input v-model.trim="form.guildId" placeholder="请输入菜单id" />
        </el-form-item>
        <el-form-item label="频道id" prop="channelId">
          <el-input v-model.trim="form.channelId" placeholder="请输入频道id" />
        </el-form-item>

        <el-form-item label="生成数量" prop="count" v-if="title === '添加'">
          <el-input-number v-model="form.count" :min="1" :max="100" :precision="0" />
        </el-form-item>

        <el-form-item label="人数限制" prop="maxUser">
          <el-input-number v-model="form.maxUser" :min="1" :max="100" :precision="0" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input :rows="3" type="textarea" v-model.trim="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" :loading="formLoading">确 定 </el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <PanelBatchUpdate @refresh="getList" ref="bactchUpdateInstance"></PanelBatchUpdate>
  </div>
</template>

<script setup name="Index">
import { listApi, createApi, deleteApi, updateApi, listAllApi, batchDeleteApi } from "@/api/base/index.js";
import usePagination from "@/hooks/usePagination";
import { deepClone } from "@/utils";
import { ElMessage } from "element-plus";
import { useRoute } from "vue-router";
import MAP, { getEnumLabel } from "@/enum/index.js";
import PanelBatchUpdate from "./components/update-dialog.vue";
import * as XLSX from "xlsx";
import axios from "axios";
import dayjs from "dayjs";

// const router = useRouter();,categoryMap
const { proxy } = getCurrentInstance();
const { pagination, total } = usePagination();
const route = useRoute();

const type = route.meta.type || 0;

const list = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const title = ref("");
const bactchUpdateInstance = ref(null);

const canEdit = computed(() => !type);
const currentParams = computed(() => {
  const obj = deepClone(unref(queryParams.value));
  const [stm, etm] = obj.date || [];
  if (stm) {
    obj.createTimeStart = stm;
  }
  if (etm) {
    obj.createTimeEnd = etm;
  }
  delete obj.date;
  return obj;
});

const data = reactive({
  form: {},
  queryParams: {
    type,
  },
  rules: {
    token: [{ required: true, message: "token不能为空", trigger: "blur" }],
  },
  formLoading: false,
});

const { queryParams, form, rules, formLoading } = toRefs(data);

// 批量更新操作
const batchUpdate = () => {
  bactchUpdateInstance.value.init(ids.value);
};

// 导出所选条件数据
const exportAll = async () => {
  loading.value = true;
  const response = [];
  try {
    const res = await listAllApi({
      ...currentParams.value,
    });
    response.push(...res.rows);
  } catch (error) {}
  loading.value = false;
  if (response.length === 0) {
    ElMessage.warning("数据为空");
    return;
  }

  const keys = {
    key: "授权码",
    token: "token",
    pCount: "使用次数",
    type: "账号类型",
    createTime: "创建时间",
    channelId: "渠道id",
    guildId: "导航id",
    maxUser: "最多服务器数",
    remark: "备注",
  };
  const keysName = Object.keys(keys);
  const valuesName = keysName.map((key) => keys[key]);
  const data = response.map((item) => {
    return keysName.map((key) => {
      if (key === "type") {
        return getEnumLabel(MAP.categoryMap, item[key]);
      }
      return item[key];
    });
  });
  data.unshift(valuesName);
  // const data = [
  //   ["姓名", "年龄", "城市"],
  //   ["John Doe", 30, "New York"],
  //   ["Jane Doe", 25, "San Francisco"],
  //   ["Bob Smith", 35, "Los Angeles"],
  // ];

  // 创建一个工作簿
  const workbook = XLSX.utils.book_new();

  // 创建一个工作表
  const worksheet = XLSX.utils.aoa_to_sheet(data);

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, "数据");

  // 将工作簿转为二进制数据
  XLSX.writeFile(workbook, "用户列表.xlsx");

  // // 创建下载链接
  // const link = document.createElement("a");
  // link.href = window.URL.createObjectURL(excelBlob);
  // link.download = "用户列表.xlsx";

  // // 触发点击链接进行下载
  // link.click();

  // // 释放对象URL，防止内存泄漏
  // window.URL.revokeObjectURL(link.href);
};

// 删除操作
const deleteHandler = (row) => {
  proxy.$modal
    .confirm("是否确认删除数据项?")
    .then(function () {
      return deleteApi({
        key: row.key,
      });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};

//
const checkAccount = async (row) => {
  loading.value = true;
  try {
    await axios.get(`https://discord.com/api/v9/users/@me/billing/payment-sources`, {
      headers: {
        Authorization: row.token,
      },
    });
    row.online = true;
    proxy.$modal.msgSuccess("token账号有效");
  } catch (error) {
    if (error.response.status === 401) {
      row.online = false;
      ElMessage.error("token账号无效");
    } else {
      ElMessage.error("未知错误");
    }
  }
  loading.value = false;
};

// 批量删除
// 删除操作
const batchDelete = () => {
  proxy.$modal
    .confirm("是否批量删除数据项?请注意，删除之后将无法恢复")
    .then(function () {
      return batchDeleteApi({
        ids: ids.value.map((v) => v.key),
      });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 查询角色列表 */
function getList() {
  loading.value = true;
  listApi({
    ...currentParams.value,
    pageNo: pagination.current,
    pageSize: pagination.size,
  })
    .then((response) => {
      list.value = response.rows.map((item) => {
        item.updateTime = dayjs(item.updateTime).format("YYYY-MM-DD HH:mm:ss");
        return item;
      });
      total.value = response.total;
    })
    .finally(() => {
      loading.value = false;
    });
}
/** 搜索按钮操作 */
function handleQuery() {
  // pagination.current = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.date = "";
  handleQuery();
}

/** 重置新增的表单以及其他数据  */
function reset() {
  // menuExpand.value = false;
  // menuNodeAll.value = false;
  // deptExpand.value = true;
  // deptNodeAll.value = false;
  proxy.resetForm("roleRef");
  form.value = {};
}

/** 添加角色 */
function handleAdd() {
  reset();
  form.value.count = 1;
  form.value.type = type || "";
  open.value = true;
  title.value = "添加";
}

/** 修改角色 */
async function handleUpdate(row) {
  reset();
  title.value = "修改";
  form.value = deepClone(unref(row));
  open.value = true;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate(async (valid) => {
    if (valid) {
      formLoading.value = true;
      try {
        if (title.value === "修改") {
          // 更新
          await updateApi(unref(form.value));
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        } else {
          // 保存
          if (form.value.count > 1) {
            form.value.key = "";
          }
          await createApi(unref(form.value));
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }
      } catch (error) {}
      formLoading.value = false;
    }
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

getList();
</script>

<style lang="scss" scoped>
.on-default {
  color: var(--el-color-primary);
}

.on-success {
  color: var(--el-color-success);
}

.on-error {
  color: var(--el-color-error);
}
</style>
